package io.iec.edp.caf.tenancy.service.manager;

import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.common.JSONSerializer;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.tenancy.api.ITenantService;
import io.iec.edp.caf.tenancy.api.entity.AppInstanceInfo;
import io.iec.edp.caf.tenancy.api.entity.DbConnectionInfo;
import io.iec.edp.caf.tenancy.api.entity.SuDbMapping;
import io.iec.edp.caf.tenancy.api.entity.Tenant;
import io.iec.edp.caf.tenancy.core.service.DbMappingManager;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class TenancyRestService {

    private ITenantService tenantService = SpringBeanUtils.getBean(ITenantService.class);
    private DbMappingManager dbMappingManager = SpringBeanUtils.getBean(DbMappingManager.class);

    public Map<String, Object> getTenantInfo(int tenantId) {
        Map<String,Object> resultMap = new HashMap<>();
        List<AppInstanceInfo> appInses = tenantService.getAllAppInstInfos(tenantId);
        if(appInses.size()!= 1){
            throw new RuntimeException("tenant: "+tenantId+" has no appInstanceInfo or has more than one info, info: "+ appInses);
        }
        //获取当前租户的appInstance信息
        AppInstanceInfo appIns = appInses.get(0);

        String appId = appIns.getId();
        if(appId==null||appId.equals("")){
            throw new RuntimeException("tenant: "+tenantId+" has wrong appInstance information");
        }

        //获取当前实例下的所有su配置信息
        List<SuDbMapping> suDbs = dbMappingManager.getAll(appId);
        //su信息按su名称排序
        if(suDbs != null)
            suDbs = suDbs.stream().sorted(Comparator.comparing(SuDbMapping::getSu)).collect(Collectors.toList());
        List<DbConnectionInfo> dbInfos = tenantService.getAllDBConnInfos(tenantId,appIns.getCode());

        resultMap.put("appins",appIns);
        resultMap.put("sudbs",suDbs);
        resultMap.put("dbInfos",dbInfos);
        return resultMap;
    }

    public List<Tenant> getAllTenants() {
        return tenantService.getAllTenants(CAFContext.current.getLanguage());
    }


}